package com.xxja.order.utils.jwt;

import com.xxja.order.auth.user.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * jwt工具类
 */
public class JwtUtils {

    public static final long EXPIRE = 1000*60*60*24*7;  //过期时间，毫秒，一周

    //秘钥
    public static final  String APPSECRET = "JwtSecret";

    /**
     * 生成jwt
     * @param user
     * @return
     */
    public static String geneJsonWebToken(User user){

        if(user == null || user.getId() == null || user.getName() == null){
            return null;
        }
        String subject = user.getId() + "-" + user.getName();
        String token = Jwts.builder().setSubject(subject)
                .claim("id",user.getId())
                .claim("name",user.getName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE))
                .signWith(SignatureAlgorithm.HS256,APPSECRET).compact();

        return token;
    }


    /**
     * 校验token
     * @param token
     * @return
     */
    public static Claims checkJWT(String token){

        try{
            final Claims claims =  Jwts.parser().setSigningKey(APPSECRET).
                    parseClaimsJws(token).getBody();
            return  claims;

        }catch (Exception e){ }
        return null;
    }

    /**
     * 获取token中的用户信息
     * @param token 传入token
     * @return
     * @throws Exception
     */
    public static User getUserFromToken(String token) throws Exception{
        Claims body = Jwts.parser().setSigningKey(APPSECRET).parseClaimsJws(token).getBody();
        return new User(
                ObjectUtils.toLong(body.get("id")),
                ObjectUtils.toString(body.get("name")));
    }

}
